package org.douxiaoban.client.api;

import java.util.ArrayList;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

import org.douxiaoban.client.adapter.MiniBlogAdapter;
import org.douxiaoban.client.util.Panel;
import org.douxiaoban.client.R;
import org.douxiaoban.client.util.Panel.OnPanelListener;
import org.douxiaoban.client.activity.CollectionSubjectActivity;
import org.douxiaoban.client.activity.UserHomeActivity;

import org.douxiaoban.client.api.MiniBlogItemData.ItemType;
import org.douxiaoban.client.app.App;
import org.douxiaoban.client.app.Assistant;
import org.douxiaoban.client.util.BounceInterpolator;
import org.douxiaoban.client.util.ThreadTool;
import org.douxiaoban.client.util.BounceInterpolator.Type;
import org.douxiaoban.client.widget.PopupRecommend;
import org.douxiaoban.client.widget.TitleStyle.WriteMiniBlog;

import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.method.LinkMovementMethod;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.inputmethod.InputMethodManager;
import android.widget.AbsListView;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.AbsListView.OnScrollListener;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AdapterView.OnItemLongClickListener;



public class MiniBlogList extends DoubanList implements OnPanelListener, WriteMiniBlog{
	private Context mContext;
	private Handler mHandler;
	private ArrayList<String> mListMenuItemData;
	private ArrayList<MenuItemType> mListMenuItemType;
	private Panel mPanel;
	
	private DoubanListType mType;
	private EditText mEditText;
	private View mView;
	
//	private ImageButton mSendMiniblog;
	private TextView mRefresh;
	private ProgressBar mProgressHead;
	
	private String mUserId;
//	private String mUserName;
	
	private PopupRecommend mPopup;
	
	private enum MenuItemType{
		PEOPLE,
		FAVORITE, //图书电影音乐
		REPLY_SAYING,
		REPLY_RECOMMEND,
		DEL,
		UN_KNOW //打开网址
	}		

	
	public enum SendType{
		SAYING,
		REV_SAYING,
		REV_RECOMMEND
	};
	
	//当前的回应类型
	private SendType mCurrentType;
	//当前回应的id
	private String m_sCurrentId;
	
	public MiniBlogList(Context context,
						MiniBlogAdapter adapter,
						DoubanListType type, 
						View view,
						String userId){
		super(context, adapter, type, view);
		
		adapter.setParentView(view);
		
		mContext = context;
		mHandler = new CustomHandler();
		mView = view;
		mType = type;
		mUserId = userId;
		mListMenuItemData = new ArrayList<String>();
		mListMenuItemType = new ArrayList<MenuItemType>();
		
		mPanel = (Panel)mView.findViewById(R.id.topPanel);
		mPanel.setOnPanelListener(this);
		mPanel.setInterpolator(new BounceInterpolator(Type.OUT));		 
	    mEditText = (EditText)mView.findViewById(R.id.panelEdit);
	    
	    mCurrentType = SendType.SAYING;    
	    
	    mPopup = new PopupRecommend(mContext);
	    initListView(this);
	    initBtnListener();
	    
	    LayoutInflater inflater = LayoutInflater.from(context);
	    View headView = inflater.inflate(R.layout.head_view, null);
	    
	    headView.setOnClickListener(new OnClickListener(){
	    	@Override
	    	public void onClick(View v){
	    		refeshMiniBlog();
	    	}
	    });
	    mRefresh = (TextView)headView.findViewById(R.id.headViewRefresh);
	    mProgressHead = (ProgressBar)headView.findViewById(R.id.headViewProgress);
	    initHeadView();
	    
	    this.getListView().addHeaderView(headView);
	    this.getListView().setAdapter(adapter);
	    this.getListView().setAdapter(this.getAdapter());
	}
	
	//获取更多
	public void reqMiniBlog(){
	
		setIsUpdateing(true);
		int start = this.getCount() + 1;
		if(DoubanListType.CONTACTS_MINIBLOG == mType){
			ThreadTool.instace(mContext).getContactsMiniBlog(App.userId,
															  mHandler,
															  start,
															  App.max);
		}else{
			ThreadTool.instace(mContext).getUserMiniBlog(mUserId,
														  mHandler,
														  start,
														  App.max);
		}
	}
	
	//刷新
	public void refeshMiniBlog(){
//		App.userId = "android_209";
		setIsUpdateing(true);
		mRefresh.setText("获取数据");
		mProgressHead.setVisibility(View.VISIBLE);
		int start = 1;
		if(DoubanListType.CONTACTS_MINIBLOG == mType){
			ThreadTool.instace(mContext).getContactsMiniBlogRefresh(App.userId,
																	  mHandler,
																	  start,
																	  App.max);
		}else{
			ThreadTool.instace(mContext).getUserMiniBlogRefresh(mUserId,
															  mHandler,
															  start,
															  App.max);
		}
	}
	
	private class CustomHandler extends Handler{
		@Override
		public void handleMessage(Message msg){
			Bundle bundle = msg.getData();
			switch(msg.what){
			case Assistant.TOOLS_MSG_MINIBLOG:
				ThreadTool.MiniBlogSerialz serialz =
					(ThreadTool.MiniBlogSerialz)bundle.getSerializable(Assistant.TOOLS_KEY_MINIBLOG);
				if(null == serialz.m_list){
					mPopup.showToastWindow(Assistant.FAIL_POP, "获取数据失败");
				}else{
					updateMiniBlog(serialz.m_list);
//					updateMiniBlog(mMbList, serialz.m_list);
					mPanel.setVisibility(View.VISIBLE);
				}
				break;
				//刷新。。
			case Assistant.TOOLS_MSG_MINIBLOG_RE:
				mProgressHead.setVisibility(View.GONE);
				mRefresh.setText("刷新");
				
				ThreadTool.MiniBlogSerialz serialzRe =
					(ThreadTool.MiniBlogSerialz)bundle.getSerializable(Assistant.TOOLS_KEY_MINIBLOG);
				if(null == serialzRe.m_list){
					mPopup.showToastWindow(Assistant.FAIL_POP, "获取数据失败");
				}else{
					insertNewData(serialzRe.m_list);
				}
				break;
				
			case Assistant.TOOLS_MSG_SAYING:
				if(bundle.getBoolean(Assistant.TOOLS_KEY_SAYING)){
					mPopup.showToastWindow(Assistant.SUCCESS_POP, "发送成功");
				}else{
					mPopup.showToastWindow(Assistant.FAIL_POP, "发送失败");
				}
				refeshMiniBlog();
				mCurrentType = SendType.SAYING;
				resetSaying();
				break;
			}
		}
	};
	
	private void initListView(final MiniBlogList list){
		
		//滚动监听
		list.getListView().setOnScrollListener(new OnScrollListener(){
			@Override
			public void onScroll(AbsListView v, int firstVisbleItem, int visibleItemCount, int totalItemCount){
				if(firstVisbleItem + visibleItemCount == totalItemCount 
						&& !list.getIsUpdateing() 
						&& !list.getIsEnd()
						&& 0 != firstVisbleItem){
						//getMore(list);
						reqMiniBlog();
				}
			}
			@Override
			public void onScrollStateChanged(AbsListView view, int scrollState) {
				
			}
		});
		
		//短按item
		list.getListView().setOnItemClickListener(new OnItemClickListener(){
			@Override
			public void onItemClick(AdapterView<?> adapter, View v, int pos, long id){
//				clickEvent(list, pos);
//				TextView content = (TextView)v.findViewById(R.id.miniBlogContent);
//				content.setMovementMethod(LinkMovementMethod.getInstance());
			}
			
		});
		//长按监听
		list.getListView().setOnItemLongClickListener(new OnItemLongClickListener(){
			@Override
			public boolean onItemLongClick(AdapterView<?> adapter, View v, int pos, long id){
//				clickEvent(list, pos);
				return true;
			}
		});
	}
	
	
	
	/**
	 * 长按和短按的监听事件
	 * @param list 
	 * @param pos 被点击的位置！
	 */
//	private void clickEvent(MiniBlogList list, int pos){
	public void clickEvent(final MiniBlogItemData data){
		//--pos;
		//第一项为head，做刷新操作
//		if(0 == pos--){
//			refeshMiniBlog();
//			return;
//		}
		initMenuData(data);
//		final MiniBlogItemData data = (MiniBlogItemData)list.getAdapter().getItem(pos);
//		final int listIndex = pos;
		DialogInterface.OnClickListener listener = new DialogInterface.OnClickListener() {
			
			@Override
			public void onClick(DialogInterface arg0, int posDlg) {
				// TODO Auto-generated method stub
				//clickItem(posList, posDlg);
				sendIntent(data, posDlg);
				
			}
			
		};	
		int size = mListMenuItemData.size();
		String [] strList = (String [])mListMenuItemData.toArray(new String[size]);
		new AlertDialog.Builder(mContext)
		.setTitle("操作菜单")
		.setItems(strList, listener).show();
	}
	
	//更新更多
	public void updateMiniBlog(ArrayList<MiniBlogItemData> itemData){	
		
		if(0 == itemData.size()){
			Log.v("updateMiniBlog::itemData size", String.valueOf(itemData.size()));
			this.setIsEnd(true);
			return;
		}
		this.setIsUpdateing(false);
		int start = getOldIndex(itemData, getLastId());
		if(-1 == start){
			this.setCount(this.getCount() + App.max);
			reqMiniBlog();
			return;
		}
		//悲剧的api..不知道神马时候能更新
		setCount(getCount() + itemData.size() -start);
		
		List<MiniBlogItemData> sub = itemData.subList(start, itemData.size());
		itemData = new ArrayList<MiniBlogItemData>(sub);	
		((MiniBlogAdapter)this.getAdapter()).addDataTail(itemData);

	
		this.setIsFirst(false);
		
		//更新最后一个id
		int lastIndex = this.getAdapter().getCount() - 1;
		MiniBlogItemData item = (MiniBlogItemData)((MiniBlogAdapter)this.getAdapter()).getItem(lastIndex);
		this.setLastId(item.m_iId);
	}
	
	
	
	/**
	 * 更新刷新操作,要对插入位置做分析
	 * 
	 * @param list 获取到的新数据
	 */
	private void insertNewData( ArrayList<MiniBlogItemData> itemData){
		mProgressHead.setVisibility(View.GONE);
		mRefresh.setText("刷新");
		
		if(itemData.size() < 20){
			this.setIsEnd(true);
		}
		this.getProgressBar().setVisibility(View.GONE);
		this.getListView().setVisibility(View.VISIBLE);
		
		int index = getNewIndex(itemData, getFirstId());
		if(-1 == index){
			return;
		}
		List<MiniBlogItemData> sub = itemData.subList(0, index);
		itemData = new ArrayList<MiniBlogItemData>(sub);

		MiniBlogAdapter adapter = (MiniBlogAdapter)getAdapter();
		adapter.addDataPre(itemData);
		if(this.getIsFirst()){
			this.setIsFirst(false);
			updateLastId();
			this.setCount(this.getCount() + itemData.size());
		}
		updateFirstId();
		//补偿留给addmore
		//this.setCount(this.getCount() + index);
		this.setIsUpdateing(false);
	}
		
	//更新firstID  
	private void updateFirstId(){
		int id = ((MiniBlogAdapter)getAdapter()).getFirstId();
		setFirstId(id);
	}
	
	//更新lastID
	private void updateLastId(){
		int id = ((MiniBlogAdapter)getAdapter()).getLastId();
		setLastId(id);
	}
	
	//刷新操作的位置分析
	private int getNewIndex(ArrayList<MiniBlogItemData> list,int id){
		for(int index = list.size()-1; index >=0 ; index--){
			if(list.get(index).m_iId > id){
				//作为右边界
				return index + 1;
			}			
		}
		return -1;
	}
	
	/**
	 * 获取更多时候的位置分析
	 * @param list 获取到的数据
	 * @param id   当前最后一个item的id值
	 * @return
	 */
	private int getOldIndex(ArrayList<MiniBlogItemData> list,int id){
		for(int index = 0; index != list.size(); index++){
			if(list.get(index).m_iId < id){
				return index;
			}			
		}
		return -1;
	}
	
	//监听发送和取消按钮
	private void initBtnListener(){
		Button btnOk = (Button)mView.findViewById(R.id.miniblog_ok);
		Button btnCancel = (Button)mView.findViewById(R.id.miniblog_cancel);
		
		btnOk.setOnClickListener(new OnClickListener(){
			@Override
			public void onClick(View view){
				sendMiniBlog();
			}
		});
		btnCancel.setOnClickListener(new OnClickListener(){
			@Override
			public void onClick(View view){
				resetSaying();
			}
			
		});
	}

	private void sendMiniBlog(){
		
		String content = mEditText.getText().toString();
		if(0 == content.length()){
			Toast.makeText(mContext, "发送内容不能为空", Toast.LENGTH_SHORT).show();
		}else{
			  InputMethodManager m = (InputMethodManager)mEditText.getContext().
				getSystemService(Context.INPUT_METHOD_SERVICE);
			  m.hideSoftInputFromWindow(mEditText.getWindowToken(), 0);
			  mPanel.setOpen(false, true);
			
			if(SendType.SAYING == mCurrentType){
				ThreadTool.instace(mContext).createSaying(content, mHandler);
			}else if (SendType.REV_SAYING == mCurrentType){
				ThreadTool.instace(mContext).revSaying(content, m_sCurrentId, mHandler);
			}else if(SendType.REV_RECOMMEND == mCurrentType){
				ThreadTool.instace(mContext).revRecommendations(content, m_sCurrentId, mHandler);
			}
		}

		
		
	}
	
	/**
	 * 重置我说,清空输入,收起下拉列表
	 */
	private void resetSaying(){
		//收起键盘
        InputMethodManager m = (InputMethodManager)mEditText.getContext().
        							getSystemService(Context.INPUT_METHOD_SERVICE);
        m.hideSoftInputFromWindow(mEditText.getWindowToken(), 0);
        
		mPanel.setOpen(false, true);
		mEditText.setText("");
		mEditText.setHint("说点神马吧!!");
		
	}
	
	/**
	 * 弹出回应对话框
	 * @param title hint的内容
	 * @param type  回应的类型
	 * @param id    我说，或者推荐的id
	 */
	public void revBtnClick(String title, SendType type, String id){
		mCurrentType = type;
		mEditText.setHint(title);
		mEditText.requestFocus();	
		m_sCurrentId = id;
		mPanel.setOpen(true, true);	
		
		//开线程显示键盘！
		new Thread(){
			@Override
			public void  run(){
			     Timer timer = new Timer();
			     timer.schedule(new TimerTask() {
		            @Override
		            public void run() {
		                InputMethodManager m = (InputMethodManager)mEditText.getContext().
		                getSystemService(Context.INPUT_METHOD_SERVICE);
		                m.toggleSoftInput(0,InputMethodManager.HIDE_NOT_ALWAYS);
		            }
		        },1000);
			}
		}.start();
   
	}
	
	public void avatarClick(String name, String id){
		Intent intent = new Intent();
    	Bundle bundle = new Bundle();
		bundle.putString(Assistant.KEY_USER_NAME,name);
		bundle.putString(Assistant.KEY_USER_ID, id);
		intent.putExtras(bundle);
		intent.setClass(mContext, UserHomeActivity.class);
		mContext.startActivity(intent);
	}
	
    public void onPanelClosed(Panel panel){
    	resetSaying();
    }
    
    /**
     * Invoked when the panel becomes fully opened.
     */
    public void onPanelOpened(Panel panel){
    	
    }
    
    private void initHeadView(){
    	//点击回应按钮！
//    	mSendMiniblog.setOnClickListener(new OnClickListener(){
//    		@Override
//    		public void onClick(View v){
//    			revBtnClick("说点神马吧!!", SendType.SAYING, "");
//    		}
//    	});
    	
    	//点击刷新按钮
    	mRefresh.setOnClickListener(new OnClickListener(){
    		@Override
    		public void onClick(View v){
//    			mRefresh.setText("获取数据");
//    			mProgressHead.setVisibility(View.VISIBLE);
//    			refeshMiniBlog();
    			
    		}
    	});
    }
    
    /**
     * 
     * @param pos 被点击的listView的位置
     * 
     * 含用户信息的都用Contact  
     * 图书电影音乐
     */
    private void initMenuData(MiniBlogItemData data){
    	mListMenuItemType.clear();
    	mListMenuItemData.clear();
//    	MiniBlogAdapter adapter = (MiniBlogAdapter)list.getAdapter();
//    	ItemType type = adapter.getItemType(pos);
//    	MiniBlogItemData data = (MiniBlogItemData)adapter.getItem(pos);
    	
    	ItemType type = data.m_itemType;
    	mListMenuItemData.add(data.m_sName);
    	mListMenuItemType.add(MenuItemType.PEOPLE);
    	

    	switch(type){
    		case CONTACT:
    			if(data.m_sOtherUserName != null){
        			mListMenuItemData.add(data.m_sOtherUserName);
        			mListMenuItemType.add(MenuItemType.PEOPLE);
    			}
    			break;
    			
    		case BOOK:
    		case MUSIC:
    		case MOVIE:
    		case TV://测试裸婚时代（原来它属于tv！fuck！）
    			mListMenuItemData.add(data.m_sSubjectName);
    			mListMenuItemType.add(MenuItemType.FAVORITE);
    			break;
    		
    		case SAYING:
    			mListMenuItemData.add("回应"+data.m_sName);
    			mListMenuItemType.add(MenuItemType.REPLY_SAYING);
    			break;
    			//可能是推荐相册 加上相册的主人
    		case RECOMMENDATION:
    			if(null != data.m_sOtherUserName){
    				mListMenuItemData.add(data.m_sOtherUserName);
    				mListMenuItemType.add(MenuItemType.PEOPLE);
    			}
    			mListMenuItemData.add("回应"+data.m_sName);
    			mListMenuItemType.add(MenuItemType.REPLY_RECOMMEND);
    			break;
    		default:
    				break;		
    	}
    	if(null != data.mUnKnowContent && data.mUnKnowContent.length() > 0){
    		mListMenuItemData.add("打开网址：" + data.mUnKnowContent);
    		mListMenuItemType.add(MenuItemType.UN_KNOW);
    	}
    	
    	if(data.m_sUserId.equals(App.userId)){
    		mListMenuItemData.add("删除");
    		mListMenuItemType.add(MenuItemType.DEL);
    	}
    }
    
    /**
     * listView 弹出的dlg的item被点击时触发
     * 
     * @param posDlg
     */
    private void sendIntent(MiniBlogItemData data, int posDlg){
    	MenuItemType type = mListMenuItemType.get(posDlg);
    	Intent intent = new Intent();
    	Bundle bundle = new Bundle();
    	String id;
    	switch(type){
    	case PEOPLE:
    		//进它的用户主页
    		String name;
    	
    		if(posDlg == 0){
    			name = data.m_sName;
    			id = data.m_sUserId;
    		}else{
    			name = data.m_sOtherUserName;
    			id = data.m_sOtherUserId;
    		}
    		bundle.putString(Assistant.KEY_USER_NAME,name);
    		bundle.putString(Assistant.KEY_USER_ID, id);
    		intent.putExtras(bundle);
    		intent.setClass(mContext, UserHomeActivity.class);
    		mContext.startActivity(intent);
    		break;
    	case FAVORITE:
    		//进相应的主页
    		Intent toSubject = new Intent(mContext, CollectionSubjectActivity.class);
    		String subjectType;
    		if(MiniBlogItemData.FavorityType.BOOK ==  data.mFavorityType ){
    			subjectType = Assistant.STATUS_BOOK;
    		}else if(MiniBlogItemData.FavorityType.MUSIC == data.mFavorityType){
    			subjectType = Assistant.STATUS_MUSIC;
    		}else if(MiniBlogItemData.FavorityType.MOVIE == data.mFavorityType){
    			subjectType = Assistant.STATUS_MOVICE;
    		}else{
    			return;
    		}
 		
			toSubject.putExtra(Assistant.KEY_OF_INTENT_CATEGORY, subjectType);
			toSubject.putExtra(Assistant.KEY_OF_INTENT_ID, data.m_sSubjectId);
			mContext.startActivity(toSubject);
    		break;
    	case REPLY_SAYING:
    		id = String.valueOf(data.m_iId);
    		this.revBtnClick("回应"+data.m_sName, SendType.REV_RECOMMEND, id);
    		break;
    	case REPLY_RECOMMEND:
    		id = String.valueOf(data.m_iId);
    		this.revBtnClick("回应"+data.m_sName, SendType.SAYING, id);
    		break;
    	case DEL:
    		//String sId = String.valueOf(data.m_iId);
    		((MiniBlogAdapter)this.getAdapter()).delItem(data.m_iId);
    		break;
    	case UN_KNOW:
        	Uri uri=Uri.parse(data.mUnKnowContentLink);
        	Intent toWeb=new Intent(Intent.ACTION_VIEW,uri);
        	mContext.startActivity(toWeb);
    		break;
    	default:
    			break;
    	}
    }
    
    //点击title 回调
	@Override
	public void writeMiniBlog() {
		revBtnClick("说点神马吧!!", SendType.SAYING, "");
	}

	public void setUserInfo(String userId, String userName){
		mUserId = userId;
//		mUserName = userName;
	}

}
